exports.plugin = {
  name: 'papersModel',
  register: async (server) => {
    const { mongoose } = server;
    const schema = mongoose.Schema({
      papername: String,
      classname: String,
      outlines: Object,
      items: Object,
      ctime: {
        type: Date,
        default: Date.now,
      },
    });

    schema.methods = {

      // 获取问卷总数
      getPapersCount() {
        return this.model('papers').countDocuments();
      },
      // 获取问卷
      getPapers({
        page, perPage, searchField, searchValue,
      } = {
        page: 1,
        perPage: 10,
      }) {
        const conditions = {};
        if (searchField && searchValue) {
          conditions[searchField] = { $regex: new RegExp(`.*${searchValue}.*`, 'i') };
        }
        return this.model('papers').find(conditions, { password: 0, __v: 0 })
          .skip((page - 1) * perPage)
          .limit(perPage)
          .sort({ ctime: -1 });
      },
      // 添加问卷
      addPapers(data) {
        return this.model('papers').create(data);
      },
      // 根据ID获取单个问卷信息
      getPaperById(_id) {
        return this.model('papers').findById(_id, { password: 0, __v: 0 });
      },
      // 根据ID删除问卷
      deletePaperById(_id) {
        return this.model('papers').deleteOne({ _id });
      },
      // 根据多个ID批量删除问卷
      deletePapersByIds(ids) {
        return this.model('papers').deleteMany({ _id: { $in: ids } });
      },
      // 根据ID更新问卷信息
      updatePaperById(_id, data) {
        return this.model('papers').updateOne({ _id }, data);
      },
      // 判断字段值是否存在
      isExist(field, value) {
        return this.model('papers').findOne({ [field]: value });
      },
    };
    const Papers = mongoose.model('papers', schema);
    server.decorate('request', 'papersModel', new Papers());
  },
};
